app.factory('localService', [
    '$window',
    function($window) {

        var arr2str = function(arr) {
            var str = "";

            if (undefined != arr && arr.length > 0) {
                str = arr.join(',')
            }

            return str;
        }

        var str2arr = function(str) {
            var arr = [];

            if ('null' != str && undefined != str && str.length > 0) {
                var arr = str.split(',');
            }

            return arr;
        }

        var getKeys = function() {
            return str2arr(unescape($window.sessionStorage.getItem('keys')));
        }

        var setKeys = function(keys) {
            $window.sessionStorage.setItem('keys', escape(arr2str(keys)));
        }

        var addKeys = function(key) {

            var arr = getKeys();
            if (-1 == arr.indexOf(key)) {
                arr.push(key);
                setKeys(arr);
            }
        }

        var removeKeys = function(key) {

            var arr = getKeys();
            if (-1 != arr.indexOf(key)) {
                arr.splice(arr.indexOf(key), 1);
            }
            setKeys(arr);
        }

        return {
            set: function(key, value) {
                if ((typeof value == 'string') && (value.constructor == String)) {
                    $window.sessionStorage.setItem(key, escape(value));
                } else {
                    $window.sessionStorage.setItem(key, escape(JSON.stringify(value)));
                }
                addKeys(key);
            },
            get: function(key) {
                var value = undefined;
                var keys = getKeys();

                if (-1 != keys.indexOf(key)) {
                    try {
                        value = JSON.parse(unescape($window.sessionStorage.getItem(key)));
                    } catch (err) {
                        value = unescape($window.sessionStorage.getItem(key));
                    }
                }

                return value;
            },
            remove: function(key) {
                $window.sessionStorage.removeItem(key);
                removeKeys(key);
            },
            clear: function() {
                $window.sessionStorage.clear();
            }
        }
    }
]);
